package com.pig4cloud.pig.module.controller.wx;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.wx.WxPayTransaction;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.wx.IWxPayTransactionService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信支付的动账流水记录Controller
 *
 * @author ruoyi
 * @date 2022-07-18
 */
@Validated
@Api(value = "微信支付的动账流水记录控制器", tags = {"微信支付的动账流水记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/wxPay/transaction")
public class WxPayTransactionController {

    private final IWxPayTransactionService wxPayTransactionService;
//	private final ISysDictDataService sysDictDataService;
	private final IWxUserService wxUserService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询微信支付的动账流水记录列表
     */
    @ApiOperation("查询微信支付的动账流水记录列表")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:list')")
    @GetMapping("/list")
    public TableDataInfo<WxPayTransaction> list(@Validated WxPayTransaction wxPayTransaction) {
        QueryWrapper<WxPayTransaction> qw = new QueryWrapper<>();
        Map<String,Object> map = new HashMap<>();
        if(wxPayTransaction.getInOrOut()!=null){
        	qw.eq("in_or_out",wxPayTransaction.getInOrOut());
            map.put("in_or_out",wxPayTransaction.getInOrOut());
		}
		if(wxPayTransaction.getFeeType()!=null){
			qw.eq("fee_type",wxPayTransaction.getFeeType());
            map.put("fee_type",wxPayTransaction.getFeeType());
		}

		if(wxPayTransaction.getPayType()!=null){
		    qw.eq("pay_type",wxPayTransaction.getPayType());
            map.put("pay_type",wxPayTransaction.getPayType());
        }

		if(StrUtil.isNotEmpty(wxPayTransaction.getOutTradeNo())){
			qw.eq("transaction_no",wxPayTransaction.getOutTradeNo())
				.or().eq("transaction_id",wxPayTransaction.getOutTradeNo())
				.or().eq("out_trade_no",wxPayTransaction.getOutTradeNo());
		}

		if(StrUtil.isNotEmpty(wxPayTransaction.getBeginDate())){
			qw.between("create_time",wxPayTransaction.getBeginDate() + " 00:00:00",wxPayTransaction.getEndDate() + " 23:59:59");
            map.put("beginTime",wxPayTransaction.getBeginDate() + " 00:00:00");
            map.put("endTime",wxPayTransaction.getEndDate() + " 23:59:59");
		}
		qw.orderByDesc("create_time");
        TableDataInfo<WxPayTransaction> td = PageUtils.buildDataInfo(wxPayTransactionService.page(PageUtils.buildPage(),qw));
        List<WxPayTransaction> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (WxPayTransaction transaction : list){
        		WxUser wxUser = wxUserService.findById(transaction.getUserId());
        		if(wxUser!=null){

					transaction.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						transaction.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}

					if(StrUtil.isNotEmpty(wxUser.getNickName())){
						transaction.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
					}
				}
			}
		}
        map.put("in_or_out",1);
        Double inMoney = wxPayTransactionService.selectInOrOutMoney(map);
        map.put("in_or_out",0);
        Double outMoney = wxPayTransactionService.selectInOrOutMoney(map);
        Map<String,Object> mapOther = new HashMap<>();
        mapOther.put("inMoney",inMoney);
        mapOther.put("outMoney",outMoney);
        td.setOtherData(mapOther);
        return td;
    }
    @ApiOperation("查询奖励记录列表")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:list')")
    @GetMapping("/reward/list")
    public TableDataInfo<WxPayTransaction> rewardList(@Validated WxPayTransaction wxPayTransaction) {
        QueryWrapper<WxPayTransaction> qw = new QueryWrapper<>();
        if(wxPayTransaction.getFeeType()!=null){
            qw.eq("fee_type",wxPayTransaction.getFeeType());
        }

        if(wxPayTransaction.getPayType()!=null){
            qw.eq("pay_type",wxPayTransaction.getPayType());
        }

        if(wxPayTransaction.getNickName()!=null){
            qw.eq("nick_name",wxPayTransaction.getNickName());
        }
        qw.eq("in_or_out",0);
        qw.ne("fee_type","charger");
        qw.ne("fee_type","charger_refund");
        qw.ne("fee_type","egg_settle");
        if(StrUtil.isNotEmpty(wxPayTransaction.getBeginDate())){
            qw.between("create_time", wxPayTransaction.getBeginDate() + " 00:00:00",wxPayTransaction.getEndDate() + " 23:59:59");
        }
        qw.orderByDesc("create_time");
        TableDataInfo<WxPayTransaction> td = PageUtils.buildDataInfo(wxPayTransactionService.page(PageUtils.buildPage(),qw));
        List<WxPayTransaction> list = td.getData();
        list.forEach(record->{
			if(StrUtil.isNotEmpty(record.getNickName())){
				record.setNickName(EmojiParser.parseToUnicode(record.getNickName()));
			}
		});


        return td;
    }

    @ApiOperation("导出奖励记录列表")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:list')")
    @GetMapping("/rewardExport/list")
    public List rewardListExport(@Validated WxPayTransaction wxPayTransaction) {
        QueryWrapper<WxPayTransaction> qw = new QueryWrapper<>();
        if(wxPayTransaction.getFeeType()!=null){
            qw.eq("fee_type",wxPayTransaction.getFeeType());
        }
        if(wxPayTransaction.getPayType()!=null){
            qw.eq("pay_type",wxPayTransaction.getPayType());
        }
        if(wxPayTransaction.getNickName()!=null){
            qw.eq("nick_name",wxPayTransaction.getNickName());
        }
        qw.eq("in_or_out",0);
        qw.ne("fee_type","charger");
        qw.ne("fee_type","charger_refund");
        qw.ne("fee_type","egg_settle");

        qw.orderByDesc("create_time");
        List<WxPayTransaction> list = wxPayTransactionService.list(qw);
        if(CollUtil.isNotEmpty(list)){
            for (WxPayTransaction transaction : list){
                if(transaction.getCreateTime()!=null){
                    transaction.setCreateTimeStr(DateUtils.getTime(transaction.getCreateTime()));
                }

                if(StrUtil.isNotEmpty(transaction.getNickName())){
                    transaction.setNickName(EmojiParser.parseToUnicode(transaction.getNickName()));
                }

//                SysDictData dictData = sysDictDataService.selectDictData("pay_fee_type",transaction.getFeeType());
//                if(dictData != null){
//                    transaction.setFeeTypeStr(dictData.getDictLabel());
//                }
                if (transaction.getInOrOut() == 0) {
                    transaction.setInOrOutStr("出账");
                }else{
                    transaction.setInOrOutStr("进账");
                }
            }
        }
        // ExcelUtil<WxPayTransaction> util = new // ExcelUtil<>(WxPayTransaction.class);
        return  list;// util.exportExcel(list, "邀请、签到奖励数据");
    }
    /**
     * 导出微信支付的动账流水记录列表
     */
    @ApiOperation("导出微信支付的动账流水记录列表")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:export')")
    @SysLog("微信支付的动账流水记录")
    @GetMapping("/export")
    public List export(@Validated WxPayTransaction wxPayTransaction) {

		QueryWrapper<WxPayTransaction> qw = new QueryWrapper<>();
		if(wxPayTransaction.getInOrOut()!=null){
			qw.eq("in_or_out",wxPayTransaction.getInOrOut());
		}
		if(wxPayTransaction.getFeeType()!=null){
			qw.eq("fee_type",wxPayTransaction.getFeeType());
		}

        if(wxPayTransaction.getPayType()!=null){
            qw.eq("pay_type",wxPayTransaction.getPayType());
        }

		if(StrUtil.isNotEmpty(wxPayTransaction.getBeginDate())){
			qw.between("create_time",wxPayTransaction.getBeginDate() + " 00:00:00",wxPayTransaction.getEndDate() + " 23:59:59");
		}

        List<WxPayTransaction> list = wxPayTransactionService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (WxPayTransaction transaction : list){
				if(transaction.getCreateTime()!=null){
					transaction.setCreateTimeStr(DateUtils.getTime(transaction.getCreateTime()));
				}

				if(StrUtil.isNotEmpty(transaction.getNickName())){
					transaction.setNickName(EmojiParser.parseToUnicode(transaction.getNickName()));
				}

//				SysDictData dictData = sysDictDataService.selectDictData("pay_fee_type",transaction.getFeeType());
//				if(dictData != null){
//					transaction.setFeeTypeStr(dictData.getDictLabel());
//				}
				if (transaction.getInOrOut() == 0) {
					transaction.setInOrOutStr("出账");
				}else{
					transaction.setInOrOutStr("进账");
				}
			}
		}
        // ExcelUtil<WxPayTransaction> util = new // ExcelUtil<>(WxPayTransaction.class);
        return  list;// util.exportExcel(list, "微信支付的动账流水记录");
    }

    /**
     * 获取微信支付的动账流水记录详细信息
     */
    @ApiOperation("获取微信支付的动账流水记录详细信息")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:query')")
    @GetMapping("/{id}")
    public R<WxPayTransaction> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") String id) {
        WxPayTransaction wxPayTransaction = wxPayTransactionService.getById(id);
        return R.ok(wxPayTransaction);
    }

    /**
     * 新增微信支付的动账流水记录
     */
    @ApiOperation("新增微信支付的动账流水记录")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:add')")
    @SysLog("微信支付的动账流水记录")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody WxPayTransaction wxPayTransaction) {
        return R.okByRow(wxPayTransactionService.save(wxPayTransaction) ? 1 : 0);
    }

    /**
     * 修改微信支付的动账流水记录
     */
    @ApiOperation("修改微信支付的动账流水记录")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:edit')")
    @SysLog("微信支付的动账流水记录")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody WxPayTransaction wxPayTransaction) {
        return R.okByRow(wxPayTransactionService.updateById(wxPayTransaction) ? 1 : 0);
    }

    /**
     * 删除微信支付的动账流水记录
     */
    @ApiOperation("删除微信支付的动账流水记录")
    @PreAuthorize("@pms.hasPermission('module:wxPayTransaction:remove')")
    @SysLog("微信支付的动账流水记录")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable String[] ids) {
        return R.okByRow(wxPayTransactionService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
